<?php

namespace app\tools;

use Yii;
use \JPush\Client;
use \JPush\Config;
use yii\base\Exception;
use yii\web\NotFoundHttpException;

class JPushHelper
{

    /**
     * 极光推送发通知
     * 默认消息保存时间1小时
     */
    public static function pushNotifyByReg($user_id_arr, $title, $content, $extra = [])
    {
        $app_key = Yii::$app->params['jpush']['app_key'];
        $master_secret = Yii::$app->params['jpush']['master_secret'];
        $apns_production = isset(Yii::$app->params['jpush']['apns_production']) ? Yii::$app->params['jpush']['apns_production'] : false;
        if (empty($app_key) || empty($master_secret)) {
            throw new NotFoundHttpException('请联系开发人员设置app_key,master_secret');
        }
        $client = new Client($app_key, $master_secret);
        try {
            $result = $client->push()
            ->setPlatform(array('ios', 'android'))
            ->addAlias($user_id_arr)
            ->setNotificationAlert('Hi, JPush')
            ->addAndroidNotification($content, $title, 1, $extra)
            ->addIosNotification($content, 'iOS sound', '+1', true, 'iOS category', $extra)
            ->setOptions(100000, 3600, null, $apns_production)
            ->send();
            return $result;
        }catch(\JPush\Exceptions\APIRequestException $e) { 
            return false;
        }
    }

    /**
     * 极光推送发通知
     * 默认消息保存时间1小时
     */
    public static function pushNotifyAll($title, $content, $extra = [])
    {
        $app_key = Yii::$app->params['jpush']['app_key'];
        $master_secret = Yii::$app->params['jpush']['master_secret'];
        $apns_production = isset(Yii::$app->params['jpush']['apns_production']) ? Yii::$app->params['jpush']['apns_production'] : false;
        if (empty($app_key) || empty($master_secret)) {
            throw new NotFoundHttpException('请联系开发人员设置app_key,master_secret');
        }

        $client = new Client($app_key, $master_secret);
        $result = $client->push()
            ->setPlatform(array('ios', 'android'))
            ->setAudience('all')
            ->setNotificationAlert('Hi, JPush')
            ->addAndroidNotification($content, $title, 1, $extra)
            ->addIosNotification($content, 'iOS sound', Config::DISABLE_BADGE, true, 'iOS category', $extra)
            ->setOptions(100000, 3600, null, $apns_production)
            ->send();
        return $result;
    }
}